<template>
  <div class="user-management">
    <h2>用户管理系统</h2>
    
    <!-- 搜索和操作区域 -->
    <div class="toolbar">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input 
            placeholder="请输入用户名搜索" 
            v-model="searchKeyword" 
            @keyup.enter.native="searchUsers"
            clearable
            @clear="fetchUsers">
            <el-button slot="append" icon="el-icon-search" @click="searchUsers"></el-button>
          </el-input>
        </el-col>
        <el-col :span="16" style="text-align: right;">
          <el-button type="primary" @click="openAddDialog">新增用户</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 用户表单对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="currentUser" :rules="rules" ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="currentUser.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="currentUser.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentUser.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="currentUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="currentUser.address"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 用户表格 -->
    <el-table :data="pagedUsers" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column prop="password" label="密码" width="120"></el-table-column>
      <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="phone" label="电话" width="120"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: 'UserManagement',
  data() {
    return {
      allUsers: [], // 所有用户数据
      pagedUsers: [], // 当前页用户数据
      loading: false,
      dialogVisible: false,
      dialogTitle: '',
      searchKeyword: '', // 搜索关键词
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示条数
      total: 0, // 总条数
      currentUser: {
        id: null,
        username: '',
        password: '',
        nickname: '',
        email: '',
        phone: '',
        address: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.fetchUsers()
  },
  methods: {
    // 获取所有用户
    fetchUsers() {
      this.loading = true
      this.$axios.get('/user')
        .then(response => {
          this.allUsers = response.data
          this.total = this.allUsers.length
          this.updatePageData()
          this.loading = false
        })
        .catch(error => {
          console.error(error)
          this.$message.error('获取用户列表失败')
          this.loading = false
        })
    },
    
    // 更新分页数据
    updatePageData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.pagedUsers = this.allUsers.slice(start, end)
    },
    
    // 搜索用户
    searchUsers() {
      if (!this.searchKeyword) {
        this.fetchUsers()
        return
      }
      
      this.loading = true
      this.$axios.get('/user')
        .then(response => {
          this.allUsers = response.data.filter(user => 
            user.username.includes(this.searchKeyword)
          )
          this.total = this.allUsers.length
          this.currentPage = 1
          this.updatePageData()
          this.loading = false
        })
        .catch(error => {
          console.error(error)
          this.$message.error('搜索用户失败')
          this.loading = false
        })
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.updatePageData()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.updatePageData()
    },
    
    // 打开新增用户对话框
    openAddDialog() {
      this.dialogTitle = '新增用户'
      this.currentUser = {
        id: null,
        username: '',
        password: '',
        nickname: '',
        email: '',
        phone: '',
        address: ''
      }
      this.dialogVisible = true
    },
    
    // 打开编辑用户对话框
    openEditDialog(user) {
      this.dialogTitle = '编辑用户'
      this.currentUser = { ...user }
      this.dialogVisible = true
    },
    
    // 保存用户（新增或更新）
    saveUser() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          if (this.currentUser.id) {
            // 更新用户
            this.$axios.put(`/user/${this.currentUser.id}`, this.currentUser)
              .then(response => {
                this.$message.success('用户更新成功')
                this.dialogVisible = false
                this.fetchUsers()
              })
              .catch(error => {
                console.error(error)
                this.$message.error('用户更新失败')
              })
          } else {
            // 新增用户
            this.$axios.post('/user', this.currentUser)
              .then(response => {
                this.$message.success('用户添加成功')
                this.dialogVisible = false
                this.fetchUsers()
              })
              .catch(error => {
                console.error(error)
                this.$message.error('用户添加失败')
              })
          }
        } else {
          return false
        }
      })
    },
    
    // 删除用户
    deleteUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/user/${id}`)
          .then(response => {
            this.$message.success('用户删除成功')
            this.fetchUsers()
          })
          .catch(error => {
            console.error(error)
            this.$message.error('用户删除失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>